import os

import rasterio
from PyQt5.QtCore import QThread, pyqtSignal
from rasterio.windows import Window


class CropRasterByGrid(QThread):
    # 计算完成信号槽
    finishedSig = pyqtSignal(str)
    # 报错信号槽
    errorSig = pyqtSignal(str)

    def __init__(self, raster, size, out):
        super(CropRasterByGrid, self).__init__()
        self.size = size
        self.raster = raster
        self.out = out

    def run(self) -> None:
        try:
            with rasterio.open(self.raster) as src:
                # Get the width and height of the image
                img_width = src.width
                img_height = src.height

                # Calculate the number of tiles in each dimension
                num_tiles_x = img_width // self.size
                num_tiles_y = img_height // self.size

                # Loop through each tile
                for i in range(num_tiles_x):
                    for j in range(num_tiles_y):
                        # Calculate the window coordinates for the current tile
                        win_left = i * self.size
                        win_top = j * self.size
                        win_right = (i + 1) * self.size
                        win_bottom = (j + 1) * self.size

                        # Adjust the window coordinates if they exceed the image dimensions
                        win_right = min(win_right, img_width)
                        win_bottom = min(win_bottom, img_height)

                        # Create a Window object for the current tile
                        window = Window(win_left, win_top, win_right - win_left, win_bottom - win_top)

                        # Read the data from the window
                        tile_data = src.read(window=window)

                        # Create the output tile file name
                        tile_filename = f'tile_{i}_{j}.tif'
                        output_path = os.path.join(self.out, tile_filename)

                        # Create the output tile file
                        profile = src.profile
                        profile.update(width=window.width, height=window.height, transform=src.window_transform(window))

                        with rasterio.open(output_path, 'w', **profile) as dst:
                            dst.write(tile_data)
                        print(f"裁剪结果: {output_path}")
            self.finishedSig.emit("裁剪完成！")
        except Exception as e:
            self.errorSig.emit("裁剪报错：%s" % e)
